<template>
  <div class="article-detail">
    <h1 v-if="article.title" class="article-title">{{ article.title }}</h1>
    <div class="article-meta" v-if="article.title">
      <span>{{ article.categoryName }}</span>
      <span>{{ article.createTime | dateFormat }}</span>
      <span>阅读量: {{ article.readCount }}</span>
    </div>
    <div class="article-content" v-html="formattedContent" v-if="article.title"></div>
    <div v-else>文章加载中...</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      article: {}
    };
  },
  computed: {
    formattedContent() {
      if (!this.article.content) return '';
      // 将内容按段落分开，并为每段添加首行缩进和换行
      let content = this.article.content.replace(/(?:\r\n|\r|\n)/g, '</p><p>');
      content = `<p>${content}</p>`;
      content = content.replace(/<p><\/p>/g, '<p>&nbsp;</p>'); // 处理空段落
      return content;
    }
  },
  created() {
    this.fetchArticleDetail();
  },
  watch: {
    '$route.query.articleId': 'fetchArticleDetail'
  },
  methods: {
    fetchArticleDetail() {
      const articleId = this.$route.query.articleId;
      if (!articleId) {
        return;
      }
      this.$axios.get('/api/article/detail', { params: { articleId } })
        .then(res => {
          if (res.data.code === "001") {
            this.article = res.data.data;
          } else {
            this.notifyError(res.data.msg);
          }
        })
        .catch(() => {
          this.notifyError('请求失败');
        });
    },
    notifyError(msg) {
      this.$notify.error({
        title: '错误',
        message: msg
      });
    }
  }
};
</script>

<style scoped>
.article-detail {
  padding: 20px;
}
.article-title {
  text-align: center;
  margin-bottom: 20px;
}
.article-meta {
  margin-bottom: 20px;
  color: #999;
}
.article-content {
  max-height: 600px;
  overflow-y: auto;
  white-space: pre-wrap; /* 保留空白符和换行 */
}
.article-content p {
  text-indent: 2em; /* 首行缩进 */
  margin-bottom: 1em; /* 段落间距 */
}
</style>
